package com.spzx.product.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.product.service.ProductService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ProductReceiver {

	@Autowired
	private ProductService productService;
	@Autowired
	private RedisTemplate redisTemplate;

	// 解锁库存
	@RabbitListener(bindings = @QueueBinding(
			exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, durable = "true"),
			value = @Queue(value = MqConst.QUEUE_UNLOCK, durable = "true"),
			key = {MqConst.ROUTING_UNLOCK}
	))
	@SneakyThrows
	public void unLockStock(String orderNo, Message message, Channel channel) {
		log.info("unlockStock收到消息{}", message);
		if (StringUtils.isEmpty(orderNo)) {
			throw new ServiceException("订单号不能为空");
		} else {
			// 加锁
			String key = "order:unLock:" + orderNo;
			boolean isSetSuccess = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 10, TimeUnit.SECONDS);
			if (!isSetSuccess) {
				log.info("unLockStock，已经被处理了");
				return;
			} else {
				log.info("unLockStock{}", orderNo);
				try {
					// 解锁库存
					productService.unLockProductStock(orderNo);
				} catch (Exception e) {
					log.error("unLockStock{}", orderNo);
				} finally {
					// 解锁
					redisTemplate.delete(key);
				}
			}
		}


		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}

    //扣减库存
    /**
     * 扣减库存
     * @param orderNo  订单号
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_MINUS, durable = "true"),
            key = {MqConst.ROUTING_MINUS}
    ))
    public void minus(String orderNo, Channel channel, Message message) {
        //业务处理
        if (StringUtils.hasText(orderNo)){
            //扣减库存
            productService.minusStock(orderNo);
        }

        //手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
